/**
 * 
 */
package com.jewaton.auth.commons.filter;

import com.jewaton.auth.commons.SystemContext;
import com.jewaton.auth.commons.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * 向当前请求作用域里添加变量
 */
public class CommonVariableFilter implements Filter {
	private ServletContext servletContext;
	private static final Logger logger = LoggerFactory.getLogger(CommonVariableFilter.class);

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
        SystemContext systemContext = SystemContext.getContext();
        try {
            HttpServletRequest httpServletRequest=(HttpServletRequest) request;
            request.setAttribute("ctx", httpServletRequest.getContextPath());
            systemContext.put(SystemContext.WEB_BASE_DIR, WebUtils.getRealPath(servletContext, File.separator));
            ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
            systemContext.put(SystemContext.SPRING_APPLICATION_CONTEXT, applicationContext);
            Object pcAccount = httpServletRequest.getSession().getAttribute(Constants.SESSION_PC_ACCOUNT);
            if(pcAccount!=null) systemContext.put(SystemContext.CURRENT_ACCOUNT, pcAccount);
            systemContext.put(SystemContext.HTTP_REQUEST_MOTHOD, httpServletRequest.getMethod());
            systemContext.put(SystemContext.HTTP_REQUEST, httpServletRequest);
            chain.doFilter(request, response);
        }catch(Exception e){
        	logger.error(e.getMessage(),e);
        } finally {
              SystemContext.destory();
        }
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		servletContext=arg0.getServletContext();
	}

}
